package com.keba.otp.db.mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.bouncycastle.util.encoders.Hex;

import com.keba.otp.core.Tempkey;
import com.keba.otp.db.TempkeysDAO;

/**
 * A MySQL adatbazis Tempkeys tablajanak lekerdezesere, modositasara szolgalo DAO 
 * @author vlewir
 *
 */
public class MySQLTempkeysDAO implements TempkeysDAO {

	public MySQLTempkeysDAO() {
		
	}
	
	@Override
	public List<Tempkey> getAllTempkeys() {
		return null;
	}

	/**
	 * Visszateriti a idnek megfelelo Key-t
	 * @param id a megkapni kivant Key a tablaban
	 */
	@Override
	public Tempkey getKeyById(String id) {
		Tempkey ret = null;
		Connection conn = null;
		try {
			conn = MySQLConnection.getConnection();
			Statement sm = conn.createStatement();
			ResultSet rs = sm.executeQuery("SELECT * from tempkeys WHERE key_id = \"" + id + "\"");
			rs.first();
			ret = new Tempkey(rs.getString(1),Hex.decode(rs.getString(2)));
			rs.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		return ret;
	}

	/**
	 * Beszur egy Tempkey-t az abatbazis Tempkeys tablajaba
	 * @param t a beszurni kivant Tempkey
	 */
	@Override
	public boolean insertTempkey(Tempkey t) {	
		Connection conn = null;
		boolean ret = false;
		try {
			conn = MySQLConnection.getConnection();
			Statement sm = conn.createStatement();
			sm.executeUpdate("INSERT into tempkeys VALUES ( \"" + 
					t.getKeyId()  + "\", \"" + 
					new String(Hex.encode(t.getKey()))   + "\")");
			ret = true;
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	 * Torli a Tempkeyt
	 * @param t a Tempkey melyet kell torolni
	 */
	@Override
	public boolean removeTempkey(Tempkey t) {
		Connection conn = null;
		boolean ret = false;
		try {
			conn = MySQLConnection.getConnection();
			Statement sm = conn.createStatement();
			sm.executeUpdate("DELETE FROM tempkeys WHERE key_id = \"" + t.getKeyId() + "\"");
			ret = true;
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

}
